import * as Cesium from 'cesium'

export default class FlightControl {
  constructor(viewer) {
    this.viewer = viewer
    this.isFlying = false
    this.preUpdateEventRemover = null
    this.positionProperty = null
    this.orientationProperty = null
  }

  // 初始化飞行路径
  initializeFlightPath(flightPath) {
    if (!this.viewer) return

    // 设置时间
    const startTime = Cesium.JulianDate.fromDate(new Date())
    const stopTime = Cesium.JulianDate.addSeconds(
      startTime,
      flightPath[flightPath.length - 1].time,
      new Cesium.JulianDate()
    )

    this.viewer.clock.startTime = startTime
    this.viewer.clock.stopTime = stopTime
    this.viewer.clock.currentTime = startTime.clone()
    this.viewer.clock.multiplier = 1
    this.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
    this.viewer.clock.shouldAnimate = false

    // 创建位置和方向的插值器
    this.positionProperty = new Cesium.SampledPositionProperty()
    this.orientationProperty = new Cesium.SampledProperty(Cesium.Quaternion)

    flightPath.forEach(keyframe => {
      const time = Cesium.JulianDate.addSeconds(
        this.viewer.clock.startTime,
        keyframe.time,
        new Cesium.JulianDate()
      )

      const position = Cesium.Cartesian3.fromDegrees(
        keyframe.position.longitude,
        keyframe.position.latitude,
        keyframe.position.height
      )
      this.positionProperty.addSample(time, position)

      const orientation = Cesium.Quaternion.fromHeadingPitchRoll(
        new Cesium.HeadingPitchRoll(
          keyframe.orientation.heading,
          keyframe.orientation.pitch,
          keyframe.orientation.roll
        )
      )
      this.orientationProperty.addSample(time, orientation)
    })

    // 初始化完成后飞到起始位置
    this.flyToStart(flightPath[0])
  }

  // 检查是否到达终点
  isFlightCompleted() {
    const currentTime = Cesium.JulianDate.secondsDifference(
      this.viewer.clock.currentTime,
      this.viewer.clock.startTime
    )
    const totalTime = Cesium.JulianDate.secondsDifference(
      this.viewer.clock.stopTime,
      this.viewer.clock.startTime
    )
    return currentTime >= totalTime
  }

  // 开始飞行
  startFlight(onComplete) {
    if (!this.viewer) return

    // 清除之前的事件监听
    if (this.preUpdateEventRemover) {
      this.preUpdateEventRemover()
    }

    // 检查是否已到达终点，如果是则重置到起点
    if (this.isFlightCompleted()) {
      this.viewer.clock.currentTime = this.viewer.clock.startTime.clone()
    }

    // 开始动画
    this.viewer.clock.shouldAnimate = true
    this.isFlying = true

    // 在每一帧渲染前执行
    // 当我们添加事件监听器时，Cesium 返回一个移除该监听器的函数
    const eventCallback = this.viewer.scene.preUpdate.addEventListener(() => {
      const position = this.positionProperty.getValue(this.viewer.clock.currentTime)
      const orientation = this.orientationProperty.getValue(this.viewer.clock.currentTime)
      
      if (position && orientation) {
        this.viewer.scene.camera.setView({
          destination: position,
          orientation: {
            heading: Cesium.HeadingPitchRoll.fromQuaternion(orientation).heading,
            pitch: Cesium.HeadingPitchRoll.fromQuaternion(orientation).pitch,
            roll: Cesium.HeadingPitchRoll.fromQuaternion(orientation).roll
          }
        })
      }

      // 终点检测逻辑
      if (this.isFlightCompleted()) {
        console.log('Flight completed')
        this.stopFlight()
        this.isFlying = false
        if (onComplete) onComplete()
      }
    })

    // 保存事件移除器
    this.preUpdateEventRemover = eventCallback
  }

  // 停止飞行
  stopFlight() {
    if (!this.viewer) return
    this.viewer.clock.shouldAnimate = false
    this.isFlying = false
    if (this.preUpdateEventRemover) {
      this.preUpdateEventRemover()
    }
  }

  // 重置飞行
  resetFlight(startPoint) {
    if (!this.viewer) return
    
    // 停止当前飞行
    this.stopFlight()
    
    // 重置时间
    this.viewer.clock.currentTime = this.viewer.clock.startTime.clone()
    
    // 飞回起始位置
    this.flyToStart(startPoint)
  }

  // 飞到起始位置
  flyToStart(startPoint) {
    if (!this.viewer) return
    
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        startPoint.position.longitude,
        startPoint.position.latitude,
        startPoint.position.height
      ),
      orientation: {
        heading: startPoint.orientation.heading,
        pitch: startPoint.orientation.pitch,
        roll: startPoint.orientation.roll
      },
      duration: 2
    })
  }

  // 销毁
  destroy() {
    if (this.preUpdateEventRemover) {
      this.preUpdateEventRemover()
    }
    this.viewer = null
  }
} 




// {
//     "flightPath": [
//       {
//         // 1. 位置参数
//         "position": {
//           "longitude": 116.4074,    // 经度：东经116.4074度
//           "latitude": 39.9042,      // 纬度：北纬39.9042度
//           "height": 1000           // 高度：距地面1000米
//         },
//         // 2. 方向参数
//         "orientation": {
//           "heading": 0,    // 航向角：0度表示正北，90度表示正东，180度表示正南，270度表示正西
//           "pitch": -30,    // 俯仰角：负数表示向下看，正数表示向上看（-90度垂直向下，0度水平，90度垂直向上）
//           "roll": 0        // 翻滚角：表示飞机绕自身轴线的旋转（正值向右倾斜，负值向左倾斜）
//         },
//         // 3. 时间参数
//         "time": 0         // 关键帧时间点（单位：秒），0表示起始点
//       }
//     ]
//   }